import {Component, ViewChild} from '@angular/core';
import {Content, Events, IonicPage, NavParams, TextInput} from 'ionic-angular';
import {User} from "../../providers/user/user";
import {SocketProvider} from "../../providers/socket/socket";

/**
 * Generated class for the SocketPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-socket',
  templateUrl: 'socket.html',
})
export class SocketPage {

  @ViewChild(Content) content: Content;
  @ViewChild('chat_input') messageInput: TextInput;

  msgList: ChatMessage[] = [];
  user: any;
  toUser: any;
  editorMsg = '';
  showEmojiPicker = false;

  constructor(public navParams: NavParams,
              public userService: User,
              public socketProvider: SocketProvider,
              public events: Events) {
    this.user = this.userService._user;
    // Get the navParams toUserId parameter
    this.toUser = {
      name: navParams.data.accountName,
      id: navParams.data.id
    };
  }

  ionViewWillLeave() {
    // unsubscribe
    this.socketProvider.disconnect();
    this.socketProvider.unsubscribe();
  }

  ionViewDidEnter() {
    console.log("ionViewDidEnter")
    this.socketProvider.connect();
    //get message list
    this.scrollToBottom();
    // Subscribe to received  new message events
    this.socketProvider.subscribeGroup();
    this.socketProvider.receive().subscribe((msg) => {
      this.pushNewMsg(msg);
    });
  }

  onFocus() {
    this.showEmojiPicker = false;
    this.content.resize();
    this.scrollToBottom();
  }

  switchEmojiPicker() {
    this.showEmojiPicker = !this.showEmojiPicker;
    if (!this.showEmojiPicker) {
      this.messageInput.setFocus();
    }
    this.content.resize();
    this.scrollToBottom();
  }

  /**
   * @name getMsg
   * @returns {Promise<ChatMessage[]>}
   */
  getMsg() {

  }


  /**
   * 发送消息
   */
  sendMsg() {
    if (!this.editorMsg.trim()) return;

    let newMsg: ChatMessage = {
      messageId: Date.now().toString(),
      userId: this.user.id,
      avatar: "http://ojg32ej8x.bkt.clouddn.com/pilotGame/file/mv",
      userName: this.user.accountName,
      toUserId: this.toUser.id,
      time: new Date(),
      message: this.editorMsg,
      status: 'pending'
    };

    this.pushNewMsg(newMsg);
    this.editorMsg = '';

    if (!this.showEmojiPicker) {
      this.messageInput.setFocus();
    }
    this.socketProvider.sendGroupMsg(newMsg);
    let index = this.getMsgIndexById(newMsg.messageId);
    setTimeout(() => {
      if (index !== -1) {
        this.msgList[index].status = 'success';
      }
    }, 1500);

  }

  /**
   * 接收新消息
   * @name pushNewMsg
   * @param msg
   */
  pushNewMsg(msg: ChatMessage) {
    console.log("pushNewMsg", msg);
    const userId = this.user.id, toUserId = this.toUser.id;
    // Verify user relationships
    if (msg.userId === userId && msg.toUserId === toUserId) {
      this.msgList.push(msg);
    } else if (msg.toUserId === userId && msg.userId === toUserId) {
      this.msgList.push(msg);
    }
    this.scrollToBottom();
  }

  getMsgIndexById(messageId: String) {
    return this.msgList.findIndex(e => e.messageId === messageId)
  }

  scrollToBottom() {
    setTimeout(() => {
      if (this.content.scrollToBottom) {
        this.content.scrollToBottom();
      }
    }, 400)
  }
}


export class ChatMessage {
  messageId: string;
  userId: number | string;
  avatar: string;
  userName: string;
  toUserId: number | string;
  time: any;
  message: string;
  status: string;
}
